var aHideInput = true;
var gDiff = null;

function scrollDiff(e1, id2) 
{
	var e2 = document.getElementById(id2);
	e2.scrollTop = e1.scrollTop;
	e2.scrollLeft = e1.scrollLeft
}

function handleHorizontalScroll()
{
	anOldTabe = $("#old-diff-table-panel");
	aNewTable = $("#new-diff-table-panel");
	if(anOldTabe.length && aNewTable.length){
		var aOldOverflows = (anOldTabe[0].scrollWidth > anOldTabe[0].clientWidth);
		var aNewOverflows = (aNewTable[0].scrollWidth > aNewTable[0].clientWidth);
		if (aOldOverflows || aNewOverflows) {
			anOldTabe.css('overflow-x', 'scroll');
			aNewTable.css('overflow-x', 'scroll');
		} else {
			anOldTabe.css('overflow-x', 'auto');
			aNewTable.css('overflow-x', 'auto');
		}
	}	
}
function setOverflowDirection(btn, ovf)
{
	var span = $('<span>').addClass('glyphicon');
	if(ovf) {
		span.addClass('glyphicon-chevron-up');
	} else {
		span.addClass('glyphicon-chevron-down');
	}
	btn.empty();
	btn.append(span);
}

function overflowDiff()
{
	aHideInput = !aHideInput;
	resizeView();
}

function showOverflowButton(cont, ovf)
{
	var btn = $('#diff-overflow-btn');
	setOverflowDirection(btn, ovf);
	var left = cont.width();
	var top = cont.height() -btn.outerHeight(true) - 10;
	btn.show();
	btn.css('left', left);
	btn.css('top', top);
	btn.blur();
}

function optimalDivision(iWorkHeight)
{
	$('#diff-content-panel').height('auto');
	$('.diff-table-panel').css("max-height", iWorkHeight * 0.52);
	aResultHeight = $('#diff-content-panel').outerHeight(true);
	$('#diff-input-panel').height(iWorkHeight - aResultHeight);
	$('#diff-input-panel').show();
}

function onlyResult(iWorkHeight)
{
	$('#diff-content-panel').height(iWorkHeight);
	$('.diff-table-panel').height(iWorkHeight - $('#diff-content-heading').outerHeight(true) - 30);
	$('.diff-table-panel').css('max-height', 'none');
	$('#diff-input-panel').hide();
}

function resizeCycles()
{
	var tr = $('#translations');
	tr.width(tr.parent().width());
	var tips = $('#text-compare-tips');
	tips.width(tips.parent().width());
}

function resizeView() 
{
	$('#diff-content-panel').height(0);
	$('.diff-table-panel').height('auto');
	
	var aMenuHeight = $('#diff-header-row').outerHeight(true);
	var aBtnsHeight = $('#diff-action-button').outerHeight(true);
	var aWorkHeight = $(window).height()-aMenuHeight-aBtnsHeight-30;
	var aResultHeight = 0;
	if($('#diff-content-panel').css('display') != 'none') {
		if($('.diff-table-panel').length) {
			aDiffHeight = $('.diff-table-panel')[0].scrollHeight;
			if(aDiffHeight > (aWorkHeight * 0.51))  {
				if(aHideInput) {
					onlyResult(aWorkHeight);
					showOverflowButton($('#diff-content-panel'), true);
				} else {
					optimalDivision(aWorkHeight)
					showOverflowButton($('#diff-content-panel'), false);
				}
			} else {
				optimalDivision(aWorkHeight);
				$('#diff-overflow-btn').hide();
			}
			handleHorizontalScroll();
		} else {
			aResultHeight = $('#diff-content-panel').outerHeight(true);
			$('#diff-input-panel').css("height", aWorkHeight - aResultHeight);
			$('#diff-input-panel').show();
		}
	} else {
		$('#diff-input-panel').css("height", aWorkHeight);
		$('#diff-overflow-btn').hide();
	}
	resizeCycles();
}

function displayTextInfo(iInfo) 
{
	$("#diff-content").append($('<h4>').append(iInfo).addClass("text-center"));
}

/**
 * 废弃
 */
function shareDiff() {
	$.post("/store", {diff : window.gDiff} , function(data) {
		$("#diff-share-url").html(data);
		$("#diff-share-url").attr("href", data);
		$("#diff-share-url").attr("value", data);
		$("#url-copy-button").attr('data-clipboard-text', data);
		$("#diff-share-dialog").modal("show");
	})
}

function loadDiff(data)
{
	window.gDiff = data;
	if(data.length) {
		var jData = jQuery.parseJSON(data);
		displayDiff(jData.d);
		$("#diff-old-input").html(jData.o);
		$("#diff-new-input").html(jData.n);
	}
	resizeView();
}

function displayDiff(diff)
{
	var new_idx = 0;
	var old_idx = 0;
	$('#diff-old-content tbody').empty();
	$('#diff-new-content tbody').empty();
	for(var l in diff) {
		var diff_line = diff[l];
		var old_num = $('<td>').addClass('diff-line-id');
		var old_line = $('<td>').addClass('diff-line');
		var new_num = $('<td>').addClass('diff-line-id');
		var new_line = $('<td>').addClass('diff-line');
		var o = false;
		var n = false;
		var m = false;
		for(e in diff_line.d) {
			var text = diff_line.d[e].t;
			if(diff_line.d[e].o == 0) {
				old_line.append(text);
				new_line.append(text);
				o = true;
				n = true;
			} else if (diff_line.d[e].o == 1) {
				new_line.append('<span class="diff-insert">' + text + '</span>');
				m = true;
				n = true;
			} else if (diff_line.d[e].o == 2) {
				old_line.append('<span class="diff-delete">' + text + '</span>');
				m = true;
				o = true;
			}
		}
		if(o) {
			old_num.append(++old_idx);
			if(m) {
				old_line.addClass('diff-delete');
			}
		} else {
			old_num.append("&nbsp;");
			old_line.addClass('diff-empty');
		}
		if(n) {
			new_num.append(++new_idx);
			if(m) {
				new_line.addClass('diff-insert');
			}
		} else {
			new_num.append("&nbsp;");
			new_line.addClass('diff-empty');
		}
			
		if(diff_line.d.length > 0) {
			$('#diff-old-content tbody').append($('<tr>').append(old_num).append(old_line));
			$('#diff-new-content tbody').append($('<tr>').append(new_num).append(new_line));
		}
	}
	if($('#diff-old-content tbody tr').length > 0) {
		$('#diff-content-panel').show();
	} else {
		$('#diff-content-panel').hide();
	}
}

function resetDiff()
{
	$('#diff-old-content tbody').empty();
	$('#diff-new-content tbody').empty();
	$('#diff-content-panel').hide();
	resizeView();
}

function performAction()
{
	var o = $('#diff-old-input').val();
	var n = $('#diff-new-input').val();
	if((o.length == 0) && (n.length == 0)) {
		resetDiff();
	} else if (o == n) {
		$("#diff-equal-dialog").modal("show");
		resetDiff();
	} else {
		var btn = $('#diff-action-button');
		btn.addClass('disabled');
		btn.blur();

		var opts = {'oldDoc' : o,'newDoc': n};
	    $.post('/diff', opts, function(data) {
	    	window.gDiff = data;
	    	var jData = jQuery.parseJSON(data);
	    	displayDiff(jData.d);
	    	resizeView();
	    	$('#diff-share-button').removeClass('disabled');
	    	btn.removeClass('disabled')
		})
	}
}

$(window).resize(resizeView);
$(function () {
	var zc = new ZeroClipboard( $("#url-copy-button") );
	zc.on('ready', function (readyEvent) {
		 $("#url-copy-button").show();
    });
	
	if (/MSIE|Trident/.test(window.navigator.userAgent)) {
	  (function($) {
	    var zcContainerId = ZeroClipboard.config('containerId');
	    $('#' + zcContainerId).on('focusin', false);
	  })(window.jQuery);
	}
	
    $('#old-fileupload').fileupload({
        url: '/upload', dropZone: $('#diff-old-input')
    }).bind('fileuploaddone', function (e, data) {
    	$('#diff-old-input').val(data.result);
    });
    
    $('#new-fileupload').fileupload({
        url: '/upload', dropZone: $('#diff-new-input')
    }).bind('fileuploaddone', function (e, data) {
    	$('#diff-new-input').val(data.result);
    });
	
	$('#diff-overflow-btn').hide();
	$('#translations').cycle({ timeout: 3000, cleartype: 1, speed: 200, fit: 1, width: '100%'});
	$('#text-compare-tips').cycle({ timeout: 10000, cleartype: 1, speed: 200, fit: 1, width: '100%' });
	
    $(document).bind('drop dragover', function (e) {
    	e.preventDefault();
    });
});